package com.healthcloud.interceptor;

import com.google.common.collect.Lists;
import com.healthcloud.utils.ApiRes;
import com.healthcloud.utils.JwtUtil;
import com.healthcloud.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * APP 接口拦截器
 *
 * @author wangdi
 * @date 2018/4/17
 */
@Slf4j
public class ApiInterceptor extends HandlerInterceptorAdapter {

    /**
     * 不需要验证token的接口
     */
    private static final List<String> IGNORE_URL = Lists.newArrayList("/mp/login","/mp/autoLogin","/mp/userInfo");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        for (String ignoreUrl : IGNORE_URL) {
            if (log.isDebugEnabled()) {
                log.debug("URL:{}", request.getRequestURL().toString());
            }
            if (request.getRequestURL().toString().contains(ignoreUrl)) {
                return true;
            }
        }
        if (!JwtUtil.containToken(request)) {
            // 无token
            WebUtil.out(response, ApiRes.failure("token失效"));
            return false;
        }
        // 校验token
        if (!JwtUtil.verifyToken(request)) {
            if (log.isDebugEnabled()) {
                log.debug("无token或token失效");
            }
            WebUtil.out(response, ApiRes.failure("token失效"));
            return false;
        }
        return true;
    }
}
